﻿Imports Publics
Imports System.Windows.Forms
Imports DanhMuc

Public Class FrmCapNhatPhieuNhapKhoVatTu
    Private lstDeleteNhapCT As New List(Of String)

    Private _IDHDNhap As String
    Public Property IDHDNhap() As String
        Get
            Return _IDHDNhap
        End Get
        Set(ByVal value As String)
            _IDHDNhap = value
        End Set
    End Property

    Private _objNhapEdit As VT_HDNhap
    Public Property objNhapEdit() As VT_HDNhap
        Get
            Return _objNhapEdit
        End Get
        Set(ByVal value As VT_HDNhap)
            _objNhapEdit = value
        End Set
    End Property

    Private _ActionForm As String
    Public Property ActionForm() As String
        Get
            Return _ActionForm
        End Get
        Set(ByVal value As String)
            _ActionForm = value
        End Set
    End Property

    Private _lstSource As List(Of cls_VT_HDNhap_ChiTiet)
    Public Property lstSource() As List(Of cls_VT_HDNhap_ChiTiet)
        Get
            Return _lstSource
        End Get
        Set(ByVal value As List(Of cls_VT_HDNhap_ChiTiet))
            _lstSource = value
        End Set
    End Property

    Private _Thang As Integer
    Public Property Thang() As Integer
        Get
            Return _Thang
        End Get
        Set(ByVal value As Integer)
            _Thang = value
        End Set
    End Property

    Private _Nam As Integer
    Public Property Nam() As Integer
        Get
            Return _Nam
        End Get
        Set(ByVal value As Integer)
            _Nam = value
        End Set
    End Property

    Private Kho_Default As DM_Kho
    Private SoHDTC_Default As String
    Private NgayHoaDon_Default As Date? = Now.Date
    Private sNgayHoaDon_Default As String
    Private ThueSuat_Default As Decimal = -1
    Private SoCT_INT As Integer

    Private Sub btnThoat_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnThoat.ItemClick
        If MsgAskDelete("Chưa lưu dữ liệu, bạn có muốn thoát không?") = vMsg.vReSult.Yes Then
            Me.Close()
        End If
    End Sub

    Private Sub FrmCapNhatPhieuNhapKhoVatTu_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Escape Then
            btnThoat_ItemClick(Nothing, Nothing)
        End If
        'Ghi và đóng
        If clsDSPhimTatDefault.isCheckPhimTat(e, ELoaiPhimTat.pSAVECLOSE, btnGhiVaDong) Then
            btnGhiVaDong_ItemClick(Nothing, Nothing)
        End If
        If clsDSPhimTatDefault.isCheckPhimTat(e, ELoaiPhimTat.pDELETE) Then
            If grvHoaDon.FocusedRowHandle < 0 Then
                Return
            End If
            If MsgAskDelete("Bạn có muốn xóa dòng này không?") = vMsg.vReSult.Yes Then
                Dim strMa = grvHoaDon.GetRowCellValue(grvHoaDon.FocusedRowHandle, grdColMaVatTu).ToString
                If Not String.IsNullOrEmpty(strMa) Then
                    lstSource.Remove((From ds In lstSource Where ds.MaVatTu = strMa Select ds).FirstOrDefault)
                    grdHoaDon.RefreshDataSource()
                End If
            End If
        End If
    End Sub

    Private Sub FrmCapNhatPhieuNhapKhoVatTu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        btnGhiVaThem.Caption = BtnSaveAndAddCaption
        btnGhiVaDong.Caption = BtnSaveAndCloseCaption
        btnThoat.Caption = BtnExitCaption
        dteNgay.DateTime = GetDate(vIntKTNam, vIntKTThang, dbTV.GetDateTimeServer.Value.Day)
        lstSource = New List(Of cls_VT_HDNhap_ChiTiet)
        dteNgay.Focus()
        lbPhimTat.Text = GetLabelPhimTatCoBanCapNhatDanhMuc() & " [Ctrl + Delete]: Xóa dòng"

        Select Case ActionForm
            Case vAddAction
                txtSoPhieu.Text = GetSoCT()
            Case vEditAction, vCopyAction
                If ActionForm = vCopyAction Then
                    txtSoPhieu.Text = GetSoCT()
                End If
                txtSoPhieu.Text = objNhapEdit.SoCT
                dteNgay.DateTime = objNhapEdit.NgayCT
                txtGhiChu.Text = objNhapEdit.GhiChu
                Dim objNCC = (From ds In dbTV.DM_KhachHangs Where ds.InUsed AndAlso ds.ID = objNhapEdit.IDKhachHang Select ds).FirstOrDefault
                If objNCC IsNot Nothing Then
                    txtMaNCC.Text = objNCC.MaKhachHang
                    txtMaNCC.Tag = objNCC.ID
                    txtTenNCC.Text = objNCC.TenKhachHang
                End If

                Dim objTCNX = (From ds In dbTV.DM_TCNXes Where ds.InUsed AndAlso ds.ID = objNhapEdit.IDTCNX Select ds).FirstOrDefault
                If objTCNX IsNot Nothing Then
                    txtMaTCNX.Text = objTCNX.MaTCNX
                    txtMaTCNX.Tag = objTCNX.ID
                    txtTenTCNX.Text = objTCNX.TenTCNX
                End If
                '// Chi tiet hoa don
                lstSource = (From ds In dbTV.VT_HDNhap_ChiTiets Join sp In dbTV.VT_DM_VatTus On ds.IDVatTu Equals sp.ID _
                             Join kho In dbTV.DM_Khos On ds.IDKho Equals kho.ID _
                             Where ds.InUsed AndAlso sp.InUsed AndAlso kho.InUsed AndAlso ds.IDHDNhap = objNhapEdit.ID _
                             Order By ds.STT Select New cls_VT_HDNhap_ChiTiet With { _
                             .ID = ds.ID, .IDVatTu = ds.IDVatTu, .IDKho = ds.IDKho, .IDHDNhap = ds.IDHDNhap, _
                             .STT = ds.STT.GetValueOrDefault, .MaVatTu = sp.MaVatTu, .TenVatTu = sp.TenVatTu, .DVT = sp.DVT, _
                             .SoLuong = ds.SoLuong.GetValueOrDefault, .DonGia = ds.DonGia.GetValueOrDefault, _
                             .ThanhTien = ds.ThanhTien.GetValueOrDefault, .ThueSuat = ds.ThueSuat.GetValueOrDefault, _
                             .TienThue = ds.TienThue, .TiLeCK = ds.TiLeCK.GetValueOrDefault, .TienCK = ds.TienCK, _
                             .TienHang = ds.TienHang, .TienThanhToan = ds.TienThanhToan.GetValueOrDefault, _
                             .SoHDTC = ds.SoHDTC, .NgayHoaDon = ds.NgayHoaDon, .sNgayHoaDon = Format(ds.NgayHoaDon, "dd/MM/yyyy"), _
                             .MaKho = kho.MaKho, .IsTruocThue = ds.IsTruocThue.GetValueOrDefault}).ToList

                If lstSource IsNot Nothing Then
                    If lstSource.Count > 0 Then
                        If lstSource(0).NgayHoaDon IsNot Nothing Then
                            NgayHoaDon_Default = lstSource(0).NgayHoaDon
                            sNgayHoaDon_Default = Format(NgayHoaDon_Default, "dd/MM/yyyy")
                            SoHDTC_Default = lstSource(0).SoHDTC
                            ThueSuat_Default = lstSource(0).ThueSuat.GetValueOrDefault
                        End If
                        Kho_Default = (From ds In dbTV.DM_Khos Where ds.InUsed AndAlso ds.ID = lstSource(0).IDKho Select ds).FirstOrDefault
                        If lstSource(0).IsTruocThue Then
                            cboThue.SelectedIndex = 0
                        Else
                            cboThue.SelectedIndex = 1
                        End If
                    End If
                End If

                txtSoPhieu.Focus()
                CapNhatSTT()
                FillThongTinTong()
        End Select

        binSource.AllowNew = True
        binSource.DataSource = lstSource
        grdHoaDon.DataSource = binSource
        grvHoaDon.RefreshData()
    End Sub
    Private Function GetSoCT() As String
        Dim strSoCT As String = ""
        Try
            SoCT_INT = dbTV.Func_GetMaxSoCTNhapToanKho_VatTu(dteNgay.DateTime.Value.Year).GetValueOrDefault + 1
            strSoCT = "000000" & SoCT_INT.ToString
            strSoCT = strSoCT.Substring(strSoCT.Length - 6, 6)
        Catch ex As Exception
            strSoCT = ""
        End Try
        Return strSoCT
    End Function
    Private Sub grvHoaDon_CellValueChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles grvHoaDon.CellValueChanged
        Try
            If e Is Nothing OrElse e.Value Is Nothing Then Return
            Dim intRowHandle As Integer = grvHoaDon.FocusedRowHandle
            Select Case e.Column.Name
                Case grdColSoHDTC.Name
                    Dim strSoHD As String
                    If intRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
                        strSoHD = "00000000" & e.Value.ToString.Trim
                        SoHDTC_Default = strSoHD.Substring(strSoHD.Length - 7, 7)
                        binSource.Current.SoHDTC = SoHDTC_Default
                        If binSource.Current IsNot Nothing Then
                            If NgayHoaDon_Default Is Nothing Then NgayHoaDon_Default = Date.Now
                            If NgayHoaDon_Default IsNot Nothing Then sNgayHoaDon_Default = Format(NgayHoaDon_Default, "dd/MM/yyyy")
                            binSource.Current.NgayHoaDon = NgayHoaDon_Default
                            binSource.Current.sNgayHoaDon = sNgayHoaDon_Default
                        End If
                    End If
                    strSoHD = "00000000" & e.Value.ToString.Trim
                    binSource.Current.SoHDTC = strSoHD.Substring(strSoHD.Length - 7, 7)
                    SetMaKho()
                    Return
                Case grdColNgayHoaDon.Name
                    If intRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
                        If e.Value IsNot Nothing AndAlso e.Value.ToString.Contains("/") Then
                            Dim arr = e.Value.ToString.Split("/")
                            Dim ngay = DateSerial(CInt(arr(2)), CInt(arr(1)), CInt(arr(0)))
                            NgayHoaDon_Default = ngay
                            sNgayHoaDon_Default = ngay.ToString("dd/MM/yyyy")
                        Else
                            NgayHoaDon_Default = Nothing
                            sNgayHoaDon_Default = Nothing
                        End If
                    End If
                    SetMaKho()
                    Return
                Case grdColMaKho.Name
                    Dim strMaKhoNhap As String = e.Value.ToString
                    Dim objKho As DM_Kho = (From ds In dbTV.DM_Khos Where ds.InUsed AndAlso ds.MaKho = strMaKhoNhap Select ds).FirstOrDefault
                    If objKho IsNot Nothing Then
                        binSource.Current.IDKho = objKho.ID
                        binSource.Current.MaKho = objKho.MaKho
                        Kho_Default = objKho
                    Else
                        Dim frmChonKho As New FrmDMKho
                        frmChonKho.LaChon = True
                        frmChonKho.StartPosition = FormStartPosition.CenterScreen
                        frmChonKho.ShowDialog()
                        objKho = (From ds In dbTV.DM_Khos Where ds.InUsed AndAlso ds.ID = frmChonKho.IDKho Select ds).FirstOrDefault
                        If objKho IsNot Nothing Then
                            binSource.Current.IDKho = objKho.ID
                            binSource.Current.MaKho = objKho.MaKho
                            Kho_Default = objKho
                        Else
                            binSource.Current.IDKho = Nothing
                            binSource.Current.MaKho = Nothing
                        End If
                    End If
                    SetMaKho()
                    Return
                Case grdColMaVatTu.Name
                    Dim strMaVatTu As String = e.Value.ToString
                    Dim objVatTu As VT_DM_VatTu = (From ds In dbTV.VT_DM_VatTus Where ds.InUsed AndAlso ds.MaVatTu = strMaVatTu Select ds).FirstOrDefault
                    If objVatTu IsNot Nothing Then
                        InsertVatTu(objVatTu)
                    Else
                        Dim frmChon As New FrmDMVatTu
                        frmChon.LaChon = True
                        frmChon.StartPosition = FormStartPosition.CenterScreen
                        frmChon.ShowDialog()
                        objVatTu = (From ds In dbTV.VT_DM_VatTus Where ds.InUsed AndAlso ds.ID = frmChon.IDVatTu Select ds).FirstOrDefault
                        If objVatTu IsNot Nothing Then
                            InsertVatTu(objVatTu)
                        Else
                            binSource.Current.IDVatTu = Nothing
                            binSource.Current.MaVatTu = Nothing
                            binSource.Current.TenVatTu = Nothing
                            binSource.Current.DonGia = 0
                            binSource.Current.ThueSuat = 0
                            binSource.Current.DVT = Nothing
                        End If
                    End If

                    binSource.Current.SoHDTC = SoHDTC_Default
                    binSource.Current.NgayHoaDon = NgayHoaDon_Default
                    If NgayHoaDon_Default IsNot Nothing Then sNgayHoaDon_Default = Format(NgayHoaDon_Default, "dd/MM/yyyy")
                    binSource.Current.sNgayHoaDon = sNgayHoaDon_Default

                    If binSource.Current IsNot Nothing Then
                        If binSource.Position + 1 = binSource.Count Then
                            binSource.Current.STT = binSource.Count()
                        Else
                            If binSource.Count = 0 Then
                                binSource.Current.STT = 1
                            End If
                        End If
                    End If

                    'If binSource.Current IsNot Nothing Then
                    '    If binSource.Current.IDKho Is Nothing Then
                    '        SetMaKho()
                    '    End If
                    'End If

                    SetMaKho()
                    Return
                Case grdColSoLuong.Name
                    'binSource.Current.ThanhTien = binSource.Current.SoLuong * binSource.Current.DonGia
                    CapNhatTienThanhToan(CType(binSource.Current, cls_VT_HDNhap_ChiTiet))
                Case grdColTiLeCK.Name
                    CapNhatTienThanhToan(CType(binSource.Current, cls_VT_HDNhap_ChiTiet))
                Case grdColGiaBia.Name
                    CapNhatTienThanhToan(CType(binSource.Current, cls_VT_HDNhap_ChiTiet))
            End Select
            FillThongTinTong()
        Catch ex As Exception
            MsgInfo(ex.ToString)
        End Try
    End Sub
    Private Sub InsertVatTu(ByVal obj As VT_DM_VatTu)
        If ThueSuat_Default = -1 Then
            ThueSuat_Default = obj.ThueSuat.GetValueOrDefault
        End If
        If obj.ThueSuat.GetValueOrDefault <> ThueSuat_Default Then
            MsgInfo("Sản phẩm không cùng thuế suất trên hóa đơn")
            Exit Sub
        End If
        If (From ds In lstSource Where ds.MaVatTu = obj.MaVatTu Select ds).FirstOrDefault IsNot Nothing Then
            MsgInfo("Trùng mã vật tư")
            Exit Sub
        End If
        binSource.Current.IDVatTu = obj.ID
        binSource.Current.MaVatTu = obj.MaVatTu
        binSource.Current.TenVatTu = obj.TenVatTu
        binSource.Current.DonGia = obj.GiaBan.GetValueOrDefault
        binSource.Current.ThueSuat = obj.ThueSuat.GetValueOrDefault
        binSource.Current.IsTruocThue = (cboThue.SelectedIndex = 0)
        binSource.Current.DVT = obj.DVT

    End Sub
    Private Sub FillThongTinTong()
        txtThanhTien.EditValue = (From ds In lstSource Select ds.ThanhTien).Sum
        txtTienCK.EditValue = (From ds In lstSource Select ds.TienCK).Sum
        txtTienThue.EditValue = (From ds In lstSource Select ds.TienThue).Sum
        txtTongSoLuong.EditValue = (From ds In lstSource Select ds.SoLuong).Sum
        txtTongTien.EditValue = (From ds In lstSource Select ds.TienThanhToan).Sum
        txtThueSuat.EditValue = ThueSuat_Default
    End Sub
    Private Sub SetMaKho()
        If binSource.Current IsNot Nothing Then
            If binSource.Current.IDKho Is Nothing Then
                If Kho_Default IsNot Nothing Then
                    binSource.Current.IDKho = Kho_Default.ID
                    binSource.Current.MaKho = Kho_Default.MaKho
                Else
                    binSource.Current.IDKho = Nothing
                    binSource.Current.MaKho = Nothing
                End If
            End If
        End If
    End Sub
    Private Sub CapNhatSTT()
        Dim i As Integer = 1
        For Each item In From ds In lstSource Order By ds.STT Select ds
            item.STT = i
            i += 1
        Next
        grdHoaDon.RefreshDataSource()
    End Sub

    Private Sub grvHoaDon_FocusedColumnChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles grvHoaDon.FocusedColumnChanged
        If binSource.Current IsNot Nothing AndAlso Flag_ValidRow Then
            grvHoaDon.FocusedColumn = grdColMaVatTu
            binSource.Current.SoHDTC = SoHDTC_Default
            binSource.Current.NgayHoaDon = NgayHoaDon_Default
            binSource.Current.sNgayHoaDon = sNgayHoaDon_Default
            Flag_ValidRow = False
        End If
    End Sub

    Private Sub grvHoaDon_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles grvHoaDon.KeyDown
        If grvHoaDon.FocusedRowHandle = grvHoaDon.RowCount - 1 Then
            If grvHoaDon.FocusedColumn.Equals(grdColSoLuong) Then
                grvHoaDon.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle
                grvHoaDon.FocusedColumn = grdColMaVatTu
            End If
        End If
    End Sub
    Private Flag_ValidRow As Boolean
    Private Sub grvHoaDon_ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles grvHoaDon.ValidateRow
        If String.IsNullOrEmpty(binSource.Current.MaVatTu) Or String.IsNullOrEmpty(binSource.Current.SoLuong) Then
            binSource.RemoveCurrent()
        End If

        If grvHoaDon.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle Then
            Flag_ValidRow = True
        End If
    End Sub

    Private Sub txtGhiChu_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGhiChu.KeyDown
        If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab Then
            grvHoaDon.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle
            grvHoaDon.FocusedColumn = grdColSoHDTC
        End If
    End Sub

    Private Sub txtMaNCC_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMaNCC.Leave
        Dim strMaNCC As String = txtMaNCC.Text.Trim
        Dim objNCC = (From ds In dbTV.DM_KhachHangs Where ds.InUsed AndAlso ds.MaKhachHang = strMaNCC Select ds).FirstOrDefault
        If objNCC IsNot Nothing Then
            txtMaNCC.Text = objNCC.MaKhachHang
            txtMaNCC.Tag = objNCC.ID
            txtTenNCC.Text = objNCC.TenKhachHang
        Else
            Dim frmChon As New FrmDMKhachHang
            frmChon.LaChon = True
            frmChon.StartPosition = FormStartPosition.CenterScreen
            frmChon.ShowDialog()
            Dim strIDKhachHang As String = frmChon.IDKhachHang
            If Not String.IsNullOrEmpty(strIDKhachHang) Then
                objNCC = (From ds In dbTV.DM_KhachHangs Where ds.InUsed AndAlso ds.ID = strIDKhachHang Select ds).FirstOrDefault
                If objNCC IsNot Nothing Then
                    txtMaNCC.Text = objNCC.MaKhachHang
                    txtMaNCC.Tag = objNCC.ID
                    txtTenNCC.Text = objNCC.TenKhachHang
                Else
                    MsgInfo("Bạn chưa chọn nhà cung cấp")
                    Return
                End If
            Else
                MsgInfo("Bạn chưa chọn nhà cung cấp")
            End If
        End If
    End Sub

    Private Sub txtMaTCNX_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMaTCNX.Leave
        Dim strTCNX As String = txtMaTCNX.Text.Trim
        Dim objTCNX = (From ds In dbTV.DM_TCNXes Where ds.InUsed AndAlso ds.MaTCNX = strTCNX Select ds).FirstOrDefault
        If objTCNX IsNot Nothing Then
            txtMaTCNX.Text = objTCNX.MaTCNX
            txtMaTCNX.Tag = objTCNX.ID
            txtTenTCNX.Text = objTCNX.TenTCNX
        Else
            Dim frmChon As New FrmDMTCNX
            frmChon.LaChon = True
            frmChon.LaNhap = True
            frmChon.StartPosition = FormStartPosition.CenterScreen
            frmChon.ShowDialog()
            Dim strIDTCNX As String = frmChon.IDTCNX
            If Not String.IsNullOrEmpty(strIDTCNX) Then
                objTCNX = (From ds In dbTV.DM_TCNXes Where ds.InUsed AndAlso ds.ID = strIDTCNX Select ds).FirstOrDefault
                If objTCNX IsNot Nothing Then
                    txtMaTCNX.Text = objTCNX.MaTCNX
                    txtMaTCNX.Tag = objTCNX.ID
                    txtTenTCNX.Text = objTCNX.TenTCNX
                Else
                    MsgInfo("Bạn chưa chọn tính chất nhập xuất")
                    Return
                End If
            Else
                MsgInfo("Bạn chưa chọn tính chất nhập xuất")
            End If
        End If
    End Sub

    Private Sub btnGhiVaDong_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnGhiVaDong.ItemClick
        Dim strErr = CheckSave()
        If Not String.IsNullOrEmpty(strErr) Then
            MsgInfo(strErr)
            Return
        End If
        If SaveData() Then
            Me.Close()
            Dim objIn = (From ds In dbTV.VT_HDNhaps Where ds.InUsed And ds.ID = IDHDNhap Select ds).FirstOrDefault
            InHoaDonNhapVT(objIn)
        End If
    End Sub
    Private Function SaveData() As Boolean
        Try
            lstDeleteNhapCT.Clear()
            Select Case ActionForm
                Case vAddAction, vCopyAction
                    Dim objAdd As New VT_HDNhap
                    objAdd.ID = CreateID()
                    IDHDNhap = objAdd.ID
                    objAdd.NgayCT = dteNgay.DateTime.Value.Date
                    objAdd.SoCT = txtSoPhieu.Text.Trim
                    objAdd.SOHDTC = lstSource(0).SoHDTC
                    objAdd.ListMaKho = String.Join(",", (From ds In lstSource Where ds.MaKho IsNot Nothing AndAlso ds.MaKho.Trim <> "" Order By ds.MaKho Select ds.MaKho Distinct).ToArray)
                    objAdd.ListSoHDTC = String.Join(",", (From ds In lstSource Where ds.SoHDTC IsNot Nothing AndAlso ds.SoHDTC.Trim <> "" Order By ds.SoHDTC Select ds.SoHDTC Distinct).ToArray)
                    objAdd.IDKhachHang = txtMaNCC.Tag.ToString
                    objAdd.IDTCNX = txtMaTCNX.Tag.ToString
                    objAdd.GhiChu = txtGhiChu.Text.Trim
                    objAdd.ThueSuat = ThueSuat_Default
                    objAdd.SoLuong = (From ds In lstSource Select ds.SoLuong.GetValueOrDefault).Sum
                    objAdd.ThanhTien = (From ds In lstSource Select ds.ThanhTien.GetValueOrDefault).Sum
                    objAdd.TienThanhToan = (From ds In lstSource Select ds.TienThanhToan.GetValueOrDefault).Sum
                    objAdd.TienThue = (From ds In lstSource Select ds.TienThue.GetValueOrDefault).Sum
                    objAdd.TienCK = (From ds In lstSource Select ds.TienCK.GetValueOrDefault).Sum
                    objAdd.TienHang = (From ds In lstSource Select ds.TienHang.GetValueOrDefault).Sum
                    objAdd.IDNhanVien = vUser.CanBo.ID
                    objAdd.InUsed = True
                    objAdd.EditedOn = dbTV.GetDateTimeServer
                    Dim bolCheckTrung As Boolean = dbTV.Func_TrungSoCTNhap_VatTu(dteNgay.DateTime.Value.Year, txtSoPhieu.Text.Trim).GetValueOrDefault
                    If bolCheckTrung Then
                        objAdd.SoCT = GetSoCT()
                    End If
                    objAdd.SoCT_Int = SoCT_INT
                    dbTV.VT_HDNhaps.InsertOnSubmit(objAdd)

                    For Each item In lstSource
                        Dim objCT As New VT_HDNhap_ChiTiet
                        objCT.ID = CreateID()
                        item.CopyTo_HDNhap_ChiTiet(objCT)
                        objAdd.VT_HDNhap_ChiTiets.Add(objCT)
                    Next
                Case vEditAction
                    Dim objHDNhap = (From ds In dbTV.VT_HDNhaps Where ds.InUsed AndAlso ds.ID = objNhapEdit.ID Select ds).FirstOrDefault
                    If objHDNhap IsNot Nothing Then
                        With objHDNhap
                            IDHDNhap = objHDNhap.ID
                            .NgayCT = dteNgay.DateTime.Value.Date
                            .NgayCT = dteNgay.DateTime.Value.Date
                            .SoCT = txtSoPhieu.Text.Trim
                            .SOHDTC = lstSource(0).SoHDTC
                            .ListMaKho = String.Join(",", (From ds In lstSource Where ds.MaKho IsNot Nothing AndAlso ds.MaKho.Trim <> "" Order By ds.MaKho Select ds.MaKho Distinct).ToArray)
                            .ListSoHDTC = String.Join(",", (From ds In lstSource Where ds.SoHDTC IsNot Nothing AndAlso ds.SoHDTC.Trim <> "" Order By ds.SoHDTC Select ds.SoHDTC Distinct).ToArray)
                            .IDKhachHang = txtMaNCC.Tag.ToString
                            .IDTCNX = txtMaTCNX.Tag.ToString
                            .GhiChu = txtGhiChu.Text.Trim
                            .SoLuong = (From ds In lstSource Select ds.SoLuong.GetValueOrDefault).Sum
                            .ThanhTien = (From ds In lstSource Select ds.ThanhTien.GetValueOrDefault).Sum
                            .TienThanhToan = (From ds In lstSource Select ds.TienThanhToan.GetValueOrDefault).Sum
                            .TienThue = (From ds In lstSource Select ds.TienThue.GetValueOrDefault).Sum
                            .TienCK = (From ds In lstSource Select ds.TienCK.GetValueOrDefault).Sum
                            .TienHang = (From ds In lstSource Select ds.TienHang.GetValueOrDefault).Sum
                            .EditedOn = dbTV.GetDateTimeServer
                        End With
                        'Insert : IDChiTiet = NULL

                        For Each item As cls_VT_HDNhap_ChiTiet In From ds In lstSource Where String.IsNullOrEmpty(ds.ID) Select ds
                            Dim objCT As New VT_HDNhap_ChiTiet
                            objCT.ID = CreateID()
                            item.CopyTo_HDNhap_ChiTiet(objCT)
                            objHDNhap.VT_HDNhap_ChiTiets.Add(objCT)
                        Next
                        'Update : IDChiTiet != NULL
                        For Each item As cls_VT_HDNhap_ChiTiet In From ds In lstSource Where String.IsNullOrEmpty(ds.ID) = False Select ds
                            Dim objUpdate As VT_HDNhap_ChiTiet = (From ds In dbTV.VT_HDNhap_ChiTiets Where ds.InUsed AndAlso ds.ID = item.ID Select ds).FirstOrDefault
                            If objUpdate IsNot Nothing Then
                                item.CopyTo_HDNhap_ChiTiet(objUpdate)
                            End If
                        Next
                        'Delete : San pham co trong hoa don chi tiet ma khong co trong lstSource
                        Dim dteNgayXoa As DateTime = dbTV.GetDateTimeServer
                        For Each item In From ds In dbTV.VT_HDNhap_ChiTiets Where ds.InUsed AndAlso ds.IDHDNhap = objHDNhap.ID Select ds
                            If (From ds In lstSource Where ds.ID = item.ID Select ds).FirstOrDefault Is Nothing Then
                                item.InUsed = False
                                item.EditedOn = dteNgayXoa
                            End If
                        Next
                    End If
            End Select

            iSubmitChange()

            If ActionForm = vAddAction Or ActionForm = vCopyAction Then
                SaveLog("Phiếu nhập kho", "Thêm mới", String.Format("Số CT: {0}, ngày: {1:dd/MM/yyyy}, tổng số lượng: {2:### ### ###}, tổng tiền: {3:### ### ###}", txtSoPhieu.Text.Trim, dteNgay.DateTime.Value.Date, txtTongSoLuong.EditValue, txtTongTien.EditValue))
            ElseIf ActionForm = vEditAction Then
                SaveLog("Phiếu nhập kho", "Cập nhật", String.Format("Số CT: {0}, ngày: {1:dd/MM/yyyy}, tổng số lượng: {2:### ### ###}, tổng tiền: {3:### ### ###}", txtSoPhieu.Text.Trim, dteNgay.DateTime.Value.Date, txtTongSoLuong.EditValue, txtTongTien.EditValue))
            End If
        Catch ex As Exception
            MsgErr(ex.Message)
            Return False
        End Try
        Return True

    End Function

    Private Function CheckSave() As String
        If dteNgay.DateTime.Value.Month <> Thang Or dteNgay.DateTime.Value.Year <> Nam Then
            Return String.Format("Ngày lập không đúng thời gian hạch toán (tháng {0} năm {1})", Thang, Nam)
        End If
        If String.IsNullOrEmpty(txtMaNCC.Text.Trim) Then
            Return "Bạn chưa nhập nhà cung cấp"
        End If
        If String.IsNullOrEmpty(txtTenTCNX.Text.Trim) Then
            Return "Bạn chưa nhập tính chất nhập xuất"
        End If
        Dim bolCheckSoLuong As Boolean
        For Each item In lstSource
            If item.SoLuong.GetValueOrDefault = 0 Then
                bolCheckSoLuong = True
                Exit For
            End If
        Next
        If bolCheckSoLuong Then
            Return "Không hợp lệ khi nhập sản phẩm có số lượng bằng 0"
        End If
        If lstSource.Count = 0 Then
            Return "Bạn chưa nhập sản phẩm vào phiếu nhập"
        End If
        Return ""
    End Function

    Private Sub btnGhiVaThem_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnGhiVaThem.ItemClick
        Dim strErr = CheckSave()
        If Not String.IsNullOrEmpty(strErr) Then
            MsgInfo(strErr)
            Return
        End If
        If SaveData() Then
            Dim objIn = (From ds In dbTV.VT_HDNhaps Where ds.InUsed And ds.ID = IDHDNhap Select ds).FirstOrDefault
            InHoaDonNhapVT(objIn)
            txtSoPhieu.Text = GetSoCT()
            lstSource.Clear()
            grdHoaDon.RefreshDataSource()
        End If
    End Sub

    Private Sub cboThue_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboThue.SelectedIndexChanged
        Dim index As Integer = cboThue.SelectedIndex
        If index = 0 Then '// Don gia chua bao gom thue
            For Each item In lstSource
                item.IsTruocThue = True
                CapNhatTienThanhToan(item)
            Next
            grvHoaDon.RefreshData()
        Else
            For Each item In lstSource
                item.IsTruocThue = False
                CapNhatTienThanhToan(item)
            Next
            grvHoaDon.RefreshData()
        End If
        FillThongTinTong()
    End Sub
End Class